﻿using System;
using System.Collections.Generic;
using System.Text;
using Pixysoft.Framework.Reflection;
using Pixysoft.Weblications.Sango.Protocol.building;
using Pixysoft.Weblications.Sango.Constant;
using Pixysoft.Framework.Verifications;
using Pixysoft.Weblications.Sango.Dao;
using Pixysoft.Weblications.Sango.Formular;
using Pixysoft.Weblications.Sango.Protocol.player;
using Pixysoft.Weblications.Sango.Protocol;
using Pixysoft.Weblications.Sango.Environment;
using Pixysoft.Weblications.Sango;

namespace Pixysoft.Weblications.Sango.Command.building
{
    partial class SangoBuildingHandler
    {
        public building_upgrade building_upgrade(long buildingtypecode)
        {
            string usercode = SangoManager.Authentication();

            switch (buildingtypecode)
            {
                case CtiBuildingTypecodeCollection.MAIN:
                    {
                        return MainBuildingUpgrade(usercode, buildingtypecode);
                    }
                default:
                    {
                        return UserBuildingUpgrade(usercode, buildingtypecode);
                    }
            }
        }

        private building_upgrade UserBuildingUpgrade(string usercode, long buildingtypecode)
        {
            building_upgrade response = ReflectionManager.CreatePojo<building_upgrade>();
            response.Succeed = false;

            Entities.Usr_Profile profile = UsrProfileDao.getUsrProfile(usercode);
            Entities.Usr_Building building = UsrBuildingDao.getUserBuilding(usercode, buildingtypecode);

            long levelupCashvalue = BuildingFormular.getLevelupCashprice(building);
            if (!UsrProfileDao.tryDecreaseCashvalue(profile, levelupCashvalue))
            {
                response.Message = "现金不足";
                return response;
            }

            if (profile.Userlevel <= building.Buildinglevel)
            {
                response.Message = "无法超越总部等级";
                return response;
            }

            // startup queue

            Entities.Usr_Activity activity = UsrActivityDao.getHistory(usercode);
            long upgradetimespan = BuildingFormular.getLevelupCoolingTime(building, activity);
            Entities.Usr_Queue availableQueue = UsrQueueDao.UsrQueueStartup(usercode, CtiQueueTypecodeCollection.BUILDING_UPGRADE,
                building.Primarycode, upgradetimespan);
            if (availableQueue == null)
            {
                response.Message = "无可用建筑队列";
                return response;
            }


            IEntityNoebeTransaction command = SettingHelper.EntityTransaction;

            command.Begin(delegate()
            {
                // queue

                command.Update(availableQueue);

                // building

                UsrBuildingDao.buildingLevelup(building);
                command.Update(building);

                // 根据建筑等级类型 升级对应项目

                switch (buildingtypecode)
                {
                    case CtiBuildingTypecodeCollection.HOUSE:
                        {
                            // DO NOTHING

                            break;
                        }
                    case CtiBuildingTypecodeCollection.CAMP:
                        {
                            // 增加兵营上限

                            profile.Maxsoldiervalue = BuildingFormular.getMaxSoldierValue(building.Buildinglevel);

                            break;
                        }
                    case CtiBuildingTypecodeCollection.INSTITUTE:
                        {
                            // 开放新战略

                            foreach (Entities.Cti_Strategy orm in CityStrategyHelper.searchOpenStrategies(building.Buildinglevel))
                            {
                                Entities.Usr_Strategy strategy = StrategyDao.createStrategy(profile, orm);
                                command.Insert(strategy);
                            }

                            break;
                        }
                    case CtiBuildingTypecodeCollection.SILVER:
                        {
                            // 升级现金上限

                            profile.Maxcashvalue = BuildingFormular.getMaxCacheValue(building.Buildinglevel);

                            break;
                        }
                    case CtiBuildingTypecodeCollection.TRAIN:
                        {
                            // DO NOTHING

                            break;

                        }
                    case CtiBuildingTypecodeCollection.TRADE:
                        {
                            // 修改当日公关次数

                            activity.Tradecount = 0;

                            break;
                        }
                    case CtiBuildingTypecodeCollection.GRAIN:
                        {
                            // 增加上限

                            profile.Maxresourcevalue = BuildingFormular.getMaxResourceValue(building.Buildinglevel);

                            break;
                        }
                    default:
                        break;
                }

                // profile

                command.Update(profile);

                // history

                activity.Buildingcount = (activity.Buildingcount + 1);
                command.Update(activity);

                command.Commit();
            });

            Entities.Usr_Property property = UsrPropertyDao.getProperty(usercode);

            response.profile = UsrProfileFacade.ToProfile(profile);
            response.property = UsrProfileFacade.ToProperty(property);
            response.buildings = UsrBuildingFacade.ToBuildings(UsrBuildingDao.getUserBuildings(usercode), activity);
            response.queues = UsrQueueFacade.ToQueues(UsrQueueDao.getUsrQueues(usercode));
            response.Succeed = true;
            return response;
        }

        private building_upgrade MainBuildingUpgrade(string usercode, long buildingtypecode)
        {
            building_upgrade response = ReflectionManager.CreatePojo<building_upgrade>();
            response.Succeed = false;


            Entities.Usr_Profile profile = UsrProfileDao.getUsrProfile(usercode);
            Entities.Usr_Property property = UsrPropertyDao.getProperty(usercode);
            Entities.Usr_Activity history = UsrActivityDao.getHistory(usercode);

            Entities.Usr_Section section = UsrSectionDao.GetSection(usercode);

            Entities.Usr_Building building = UsrBuildingDao.getUserBuilding(usercode, buildingtypecode);

            Entities.Cti_Building cityBuilding = CityBuildingHelper.searchBuilding(building.Buildingtypecode);

            // check main building level.

            if (building.Buildinglevel == cityBuilding.Maxlevel)
            {
                response.Message = "主城等级达到最大。";
                return response;
            }

            // check section prosperity

            Entities.Sys_Section sysSection = SysSectionHelper.searchSectionByCode(section.Sectionserialcode);
            long playerMaxlevel = SectionFormular.GetPlayerMaxLevel(sysSection, section);

            if (building.Buildinglevel >= playerMaxlevel)
            {
                response.Message = "声望不足，无法继续升级。";
                return response;
            }

            // get cooling queue.

            Entities.Usr_Activity activity = UsrActivityDao.getHistory(usercode);
            long upgradetimespan = BuildingFormular.getLevelupCoolingTime(building, activity);
            Entities.Usr_Queue availableQueue = UsrQueueDao.UsrQueueStartup(usercode, CtiQueueTypecodeCollection.BUILDING_UPGRADE,
                building.Primarycode, upgradetimespan);
            if (availableQueue == null)
            {
                response.Message = "无可用建筑队列";
                return response;
            }

            // decrease cash

            long decreaseCashvalue = BuildingFormular.getLevelupCashprice(building);
            if (!UsrProfileDao.tryDecreaseCashvalue(profile, decreaseCashvalue))
            {
                response.Message = "银币不足";
                return response;
            }




            // open database.

            IEntityNoebeTransaction command = SettingHelper.EntityTransaction;

            command.Begin(delegate()
            {
                command.Update(availableQueue);

                // open building

                foreach (Entities.Cti_Building openCityBuilding in UsrBuildingDao.getOpenBuildingByMainLevel(usercode, building.Buildinglevel + 1))
                {
                    Entities.Usr_Building openBuilding = UsrBuildingDao.createBuilding(profile.Usercode, profile.Nickname, openCityBuilding);
                    command.Insert(openBuilding);
                }

                // building upgrade

                UsrBuildingDao.buildingLevelup(building);
                command.Update(building);

                profile.Userlevel = (building.Buildinglevel);



                if (UsrSectionDao.needUpgradeSection(profile))
                {
                    // change section

                    UsrSectionDao.upgradeSection(section);
                    command.Update(section);

                    // resource balance

                    foreach (Entities.Usr_Resource resource in UsrResourceDao.GetUserResources(usercode))
                    {
                        ResourceFormular.resourceCurrentBalance(resource, profile);
                        command.Update(resource);
                    }

                }


                // history

                history.Freebattlecount = (history.Freebattlecount + 1);
                history.Buildingcount = (history.Buildingcount + 1);
                command.Update(history);


                // update profile

                command.Update(profile);

                command.Commit();
            });

            // response

            List<Entities.Usr_Queue> queues = UsrQueueDao.getUsrQueues(usercode);

            response.profile = UsrProfileFacade.ToProfile(profile);
            response.property = UsrProfileFacade.ToProperty(property);
            response.queues = UsrQueueFacade.ToQueues(queues);
            response.buildings = UsrBuildingFacade.ToBuildings(UsrBuildingDao.getUserBuildings(usercode), history);
            response.Succeed = true;
            return response;
        }
    }

    public interface building_upgrade : ISangoResponse
    {
        player_profile profile { get;set;}
        player_property property { get;set;}

        List<player_queue> queues { get;set;}
        List<building_building> buildings { get;set;}
    }
}
